package com.hxy.travel.security;

import com.alibaba.fastjson.JSON;
import com.hxy.travel.entity.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomAccessDenieHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        if ( isAjax(httpServletRequest) ){
            Result result = new Result();
            result.setFlag(false);
            result.setMessage("没有响应权限");
            result.setData("403");
            httpServletResponse.getWriter().printf(JSON.toJSONString(result));
        }else{
            httpServletRequest.getRequestDispatcher("/pages/error/403.html").forward(httpServletRequest,httpServletResponse);
        }
    }
    public static boolean isAjax( HttpServletRequest request ){
        if (request.getHeader("accept").indexOf("application/json") > -1 || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest"))) {
            return true;
        }
        return false;
    }
}
